<?php
namespace app\controller;

use app\BaseController;
use app\Request;
use think\App;
use think\cache\driver\Redis;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\Queue;

class Test extends BaseController
{

    protected $redis;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->redis = new \Redis();
        $this->redis->connect('127.0.0.1',6379);
        $this->redis->auth('123456');
    }

    /**
     * TODO:商品定义为list_key_goods
     *      人数抢购定义为list_person_info
     */
    public function test()
    {
        $user_id = \think\facade\Request::param('user_id');
        $personLength = $this->redis->lLen('list_person_info');             //获取入队列的人数
        $lengthKey = $this->redis->lLen('list_key_goods');                  //计算商品队列信息
/*        var_dump($personLength);
        var_dump($lengthKey);*/
        //如果队列的长度小于等于商品信息长度  把人数继续如队列
        if ($lengthKey != 0)
        {
            $goodInfo = $this->redis->rPop('list_key_goods');//获取redis数据
            $data = [
                'userInfo' =>[
                    'user_id' =>$user_id,
                ],
                'goodInfo' =>$goodInfo,
            ];
            $userInfoTrue = $this->redis->lPush('list_person_info',$user_id);    //用户入队列

            $jobHandlerClassName = 'app\job\Task1';
            $jobQueueName = 'task1';
            $isPushed = \think\facade\Queue::push($jobHandlerClassName, $data, $jobQueueName);
            if ($isPushed)
            {
                Log::info("----------------------------------商品入队列成功-------------------------------------");
                return success($data,'创建订单成功！',200);
            }else
            {
                return error('创建订单失败！',$data,400);
                Log::info("----------------------------------商品入队列失败-------------------------------------");
            }
        }else
        {
            $personLength = $this->redis->del('list_person_info');
            return error('商品已抢购完成！',400);
        }

    }





    public function subscribes()
    {
        $this->redis->subscribe(["channel 1", "channel 2"], function($redis, $channel, $message) {
            echo "Channel $channel: $message";
        });
    }


}
